﻿using System;
using System.Web;
using Family.Data.Factories;
using NHibernate;

namespace Family.Data
{
    public class NHModule : IHttpModule
    {    
        #region IHttpModule Members

        private const String CONFIG_KEY = "FamilyConnectionString";

        private ITransaction transaction;
        private NHFactory factory;

        public void Init(HttpApplication context)
        {
            factory = new WebFactory(CONFIG_KEY);
            factory.Init();

            context.BeginRequest += context_BeginRequest;
            context.EndRequest += context_EndRequest;

        }

        void context_BeginRequest(object sender, EventArgs e)
        {
            WebFactory.CurrentSession = WebFactory.SessionFactory.OpenSession();
            transaction = WebFactory.CurrentSession.BeginTransaction();
        }

        void context_EndRequest(object sender, EventArgs e)
        {
            if (HttpContext.Current.Server.GetLastError() != null)
            {
                transaction.Rollback();
            }
            else
            {
                transaction.Commit();
            }
        }

        public void Dispose()
        {
            /*if (WebFactory.CurrentWebSession != null)
                WebFactory.CurrentWebSession.Dispose();*/
        }

        #endregion
    }
}
